#define _CRT_SECURE_NO_WARNINGS
#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

class Solution {
    int n, m;
    int ret;
    queue<pair<int, int>> q;
    bool vis[1010][1010] = { 0 };
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };

public:
    int rotApple(vector<vector<int> >& grid) {

        n = grid.size(), m = grid[0].size();

        for (int i = 0;i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                if (grid[i][j] == 2)
                    q.push({ i,j });
            }
        }

        while (!q.empty())
        {
            ret++;
            int sz = q.size();
            while (sz--)
            {
                auto [a, b] = q.front();
                q.pop();
                for (int i = 0;i < 4;i++)
                {
                    int x = a + dx[i];
                    int y = b + dy[i];
                    if (x >= 0 && x < n && y >= 0 && y < m && !vis[x][y] && grid[x][y] == 1)
                    {
                        q.push({ x,y });
                        vis[x][y] = true;
                    }
                }
            }
        }

        for (int i = 0;i < n;i++)
            for (int j = 0;j < m;j++)
                if (grid[i][j] == 1 && !vis[i][j])
                {
                    return -1;
                }
        return ret - 1;
    }
};

int main()
{
	return 0;
}